package com.tycoin.app.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tycoin.app.response.BaseRespose;
import com.tycoin.user.slaveentity.TycoinAddress;
import com.tycoin.user.slaveservice.TycoinAddressService;
import com.util.SendEmail;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.chuanglan.demo.SmsSendChuangLan;
import com.tycoin.account.slaveentity.TycoinAccount;
import com.tycoin.account.slaveentity.TycoinUserWallet;
import com.tycoin.account.slaverepository.TycoinUserWalletRepository;
import com.tycoin.account.slaveservice.TycoinAccountService;
import com.tycoin.account.slaveservice.TycoinUserWalletService;
import com.tycoin.user.slaveentity.TycoinUser;
import com.tycoin.user.slaveentity.TycoinUserLoginLog;
import com.tycoin.user.slaveservice.TycoinUserLoginLogService;
import com.tycoin.user.slaveservice.TycoinUserService;
import com.tycoin.utils.OkcoinHttpRequest;
import com.tycoin.utils.VerifyCodeUtils;
import com.tycoin.utils.VerifyEmail;
import com.util.DateUtils;
import com.util.HttpClientUtils;
import com.util.MD5Utils;
import com.util.PhoneFormatCheckUtils;

 
  
/**
 * 
 * 
 */
@Controller
@RequestMapping(value = { "/user" })
public class UserController  extends AbstractController{

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private TycoinUserService tycoinUserService;
	
	
	@Autowired
	private TycoinAccountService tycoinAccountService;
	
	@Autowired
	private TycoinUserLoginLogService tycoinUserLoginLogService;
	
	@Autowired
	private TycoinUserWalletService tycoinUserWalletService;

	@Autowired
	private BaseRespose baseRespose;
	private String resetCode;
	private String emailCode;
	private   int PAGENUM=5;


	/**
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/login", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public  Map<String, Object> loginUser(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
 		String userName = request.getParameter("userName");
		String passWord = request.getParameter("passWord");
		TycoinUser tycoinUser = new TycoinUser();
		Map<String, Object> map = new HashMap<>();
		VerifyEmail  t = new VerifyEmail();
		  String email = request.getParameter("email");
		  boolean  isEmail = t.isEmail(email);
 		  
		if (PhoneFormatCheckUtils.isChinaPhoneLegal(userName)) {
			    tycoinUser = tycoinUserService.findOneBymobile( userName);
 		} else if(isEmail){
			    tycoinUser  = tycoinUserService.findOneByemail(userName);
		}else{
 		    tycoinUser  = tycoinUserService.findOneByusername(userName);
		}
 	if (tycoinUser != null) {
			String salt = tycoinUser.getSalt();
			MD5Utils encoderMd5 = new MD5Utils(salt, "MD5");
			System.out.println(tycoinUser.getPassword());
			boolean passwordValid = encoderMd5.isPasswordValid(tycoinUser.getPassword(), passWord);
			if (passwordValid) {
				Cookie cookie = new Cookie("userInfo", "userName:" + java.net.URLEncoder.encode(userName, "UTF-8")
						+ ",passWord:" + tycoinUser.getPassword() + ",userId:" + tycoinUser.getId());
				cookie.setMaxAge(7200);
				cookie.setPath("/");
				//response.addCookie(cookie);
				request.getSession().setAttribute("userName", userName);
				request.getSession().setAttribute("passWord", tycoinUser.getPassword());
				request.getSession().setAttribute("userId", tycoinUser.getId());
				
				
				   //登录插入日志
				TycoinUserLoginLog tycoinUserLoginLog=new TycoinUserLoginLog();
				tycoinUserLoginLog.setUserId(tycoinUser.getId());
				tycoinUserLoginLog.setLoginTime(DateUtils.formatDateTime3(new Date()));
				tycoinUserLoginLog.setIp(getIpAddr(request));
				String addresss=super.findIpToAddress(tycoinUserLoginLog.getIp());
				tycoinUserLoginLog.setAddress(addresss);
 				tycoinUserLoginLogService.save(tycoinUserLoginLog);
  				
 				tycoinUser.setIntegral(tycoinUser.getIntegral()+2);
 				tycoinUser.setLastloginip(tycoinUserLoginLog.getIp());
 				map.put("code", "0000");
				map.put("msg", "登录成功!");

			} else {
  				map.put("code", "2000");
				map.put("msg", "用户名或密码错误!");
			}
		} else {
 				map.put("code", "1000");
			map.put("msg", "该用户不存在!");

		}
		return map;
	}
	
	
	
	
	
	@RequestMapping(value = "/findMobilePhone", produces = "application/json;charset=UTF-8" , method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> findMobile(HttpServletRequest request,HttpServletResponse response) {
		Map<String, Object> map = new HashMap<>();
		String mobilePhone=request.getParameter("mobilePhone");
        TycoinUser tycoinUser=tycoinUserService.findOneBymobile(mobilePhone);
        if(tycoinUser!=null){
        	map.put("code", 502);
        	map.put("message", "该手机号已被注册");
        }else{
          	map.put("code", 200);
        	map.put("message", "可以注册");
        }
		return map;
	}
	
	@RequestMapping(value = "/backSendCode", produces = "application/json;charset=UTF-8" , method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> backSendCode(HttpServletRequest request,HttpServletResponse response) {
		Map<String, Object> map = new HashMap<>();
		String chuanglanStr="";
		String mobilephone=request.getParameter("mobile");
		TycoinUser tycoinUser = tycoinUserService.findOneBymobile(mobilephone);
		if (tycoinUser != null) {
			// 手机号不存在！
			map.put("code", "201");
			map.put("msg", "账号已存在");
			return map;
		}
		String notifCode = DateUtils.getYzm();
 	 
		try {
			 chuanglanStr = SmsSendChuangLan.sendChuangLanSms(mobilephone, notifCode);
			map.put("code", "200");
			map.put("msg", chuanglanStr);
			map.put("notifCode", notifCode);
			

			System.out.println(notifCode);
		} catch (Exception e) {
			map.put("code", "202");
			map.put("msg", "发送验证码失败。");
			e.printStackTrace();
		}
		return map;
	}
	
	

	@RequestMapping(value = "/register", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> register(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<>();
		String mobilephone=request.getParameter("mobilephone");
		String passWord=request.getParameter("passWord");
 		TycoinUser tycoinUser = tycoinUserService.findOneBymobile( mobilephone);
		if(tycoinUser!=null){
			map.put("code", "201");
			map.put("msg", "账号已存在");
 		}else{
  			  tycoinUser=new TycoinUser();
  			tycoinUser.setMobile(mobilephone);
   		    String salt =getRandomString(8);
			MD5Utils encoderMd5 = new MD5Utils(salt, "MD5");
 		     String encodePassWord= encoderMd5.encode(passWord);
 		    tycoinUser.setSalt(salt);
 		    tycoinUser.setPassword(encodePassWord);
 			tycoinUser.setSecurityLevel(1);
 			tycoinUser.setIsRealname(0);
  		    tycoinUser= tycoinUserService.save(tycoinUser);
 		    TycoinAccount tycoinAccount=new TycoinAccount();
 		     tycoinAccount.setUserId(String.valueOf(tycoinUser.getId()));
 		     //初始化金额
 		    tycoinAccount.setUseMoney(new BigDecimal(0));
 		    tycoinAccount.setUseBtc(new BigDecimal(0));
 		    tycoinAccount.setUseLtc(new BigDecimal(0));
 		    tycoinAccount.setUseEth(new BigDecimal(0));
 		    tycoinAccount.setUseEtc(new BigDecimal(0));
 		    
 		    tycoinAccount.setNoMoney(new BigDecimal(0));
 		    tycoinAccount.setNoBtc(new BigDecimal(0));
 		    tycoinAccount.setNoLtc(new BigDecimal(0));
 		    tycoinAccount.setNoEth(new BigDecimal(0));
 		    tycoinAccount.setNoEtc(new BigDecimal(0));
 		    
 		    tycoinAccountService.save(tycoinAccount);
 		    
 		    //注册成功就登录
 			Cookie cookie = null;
			try {
				cookie = new Cookie("userInfo", "userName:" + java.net.URLEncoder.encode(mobilephone, "UTF-8")
				+ ",passWord:" + tycoinUser.getPassword() + ",userId:" + tycoinUser.getId());
			} catch (UnsupportedEncodingException e) {
			 
			}
			cookie.setMaxAge(7200);
			cookie.setPath("/");
			response.addCookie(cookie);
			request.getSession().setAttribute("userName", mobilephone);
			request.getSession().setAttribute("passWord", tycoinUser.getPassword());
			request.getSession().setAttribute("userId", tycoinUser.getId());
	       //登录插入日志
			TycoinUserLoginLog tycoinUserLoginLog=new TycoinUserLoginLog();
			tycoinUserLoginLog.setUserId(tycoinUser.getId());
			tycoinUserLoginLog.setLoginTime(DateUtils.formatDateTime3(new Date()));
			tycoinUserLoginLog.setIp(getIpAddr(request));
			String addresss=super.findIpToAddress(tycoinUserLoginLog.getIp());
			tycoinUserLoginLog.setAddress(addresss);
			tycoinUserLoginLogService.save(tycoinUserLoginLog);
 			
 
 		     map.put("code", "200");
			 map.put("msg", "注册成功");
  		}

	 
		return map;
	}

	/******
	 * 重置密码
	 * @param request
	 * @param response
	 * @return
	 */

	@RequestMapping(value = "/resetPassword",method = RequestMethod.POST)
	@ResponseBody
	public BaseRespose resetPasswd(HttpServletRequest request,HttpServletResponse response){
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		TycoinUser user=tycoinUserService.findById(Long.valueOf(userId));
		if (user==null)
		{
			baseRespose.setCode(4008);
			baseRespose.setMassage("seesion错误");
			return baseRespose;
		}
		MD5Utils encoderMd5 = new MD5Utils(user.getSalt(), "MD5");
		String password=user.getPassword();
		String password_re= (String) request.getParameter("password");
		String new_pw=(String) request.getParameter("new_password");
		String new_pw2=(String) request.getParameter("new_password2");
		String pay_password=(String) request.getParameter("pay_password");
		String msgCode=(String) request.getParameter("vcode");
		password_re=encoderMd5.encode(password_re);
		if (null==new_pw||!new_pw.equals(new_pw2)){
			baseRespose.setCode(4009);
			baseRespose.setMassage("新密码不一致");
			return baseRespose;
		}

		if (!password.equals(password_re))
		{
			baseRespose.setCode(4010);
			baseRespose.setMassage("当前密码错误");
			return baseRespose;
		}
		if (resetCode==null||msgCode==null||!resetCode.equals(msgCode)){
			baseRespose.setCode(4011);
			baseRespose.setMassage("验证码错误");
			return baseRespose;
		}
		new_pw=encoderMd5.encode(new_pw);
		user.setPassword(new_pw);
		if (pay_password!=null)
		{
			pay_password=encoderMd5.encode(pay_password);
			user.setPaymentPwd(pay_password);
		}
		tycoinUserService.save(user);
		request.getSession().invalidate();
		baseRespose.setCode(200);
		baseRespose.setMassage("修改密码成功");
		return baseRespose;
	}



	/*********
	 * 设置支付密码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/setPayPasswd",method = RequestMethod.POST)
	@ResponseBody
	public BaseRespose setPayPasswd(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		String mobile = String.valueOf(request.getSession().getAttribute("mobilephone"));
		String wechat = String.valueOf(request.getSession().getAttribute("wechat"));
		TycoinUser user=tycoinUserService.findById(Long.valueOf(userId));
		if (user==null||mobile!=null)
			user=tycoinUserService.findOneBymobile(mobile);
		if (user==null||wechat!=null)
			user=tycoinUserService.findOneByweixin(wechat);
		if (user==null)
		{
			baseRespose.setCode(4008);
			baseRespose.setMassage("seesion错误");
			return baseRespose;
		}
		MD5Utils encoderMd5 = new MD5Utils(user.getSalt(), "MD5");
		String new_pw=(String)  request.getParameter("new_password");
		String new_pw2=(String)  request.getParameter("new_password2");
		String msgCode=(String) request.getParameter("vcode");
		if (!new_pw.equals(new_pw2)){
			baseRespose.setCode(4009);
			baseRespose.setMassage("密码不一致");
			return baseRespose;
		}
		if (resetCode!=null&&!resetCode.equals(msgCode)){
			baseRespose.setCode(4011);
			baseRespose.setMassage("验证码错误");
			return baseRespose;
		}
		new_pw=encoderMd5.encode(new_pw);
		user.setPaymentPwd(new_pw);
		tycoinUserService.save(user);
		baseRespose.setCode(200);
		baseRespose.setMassage("设置支付密码成功");
		return baseRespose;
	}




	/*********
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/sendVCode", method = RequestMethod.POST)
	@ResponseBody
	public BaseRespose sendVCode(HttpServletRequest request,HttpServletResponse response,String msgTemplate) {
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		TycoinUser user=tycoinUserService.findById(Long.valueOf(userId));
		if (user==null)
		{
			baseRespose.setCode(4008);
			baseRespose.setMassage("seesion错误");
			return baseRespose;
		}
		resetCode = DateUtils.getYzm();
		String msg=sendMsgToMoblile(user.getMobile(),resetCode);
		baseRespose.setCode(200);
		baseRespose.setMassage(resetCode);
	
		return baseRespose;
	}



	public String sendMsgToMoblile(String mobile,String notifCode)  {
		try {
			return  SmsSendChuangLan.sendChuangLanSms(mobile, notifCode);
		} catch (UnsupportedEncodingException e) {
			return "send message fail";
		}
	}

	@Autowired
	TycoinAddressService tycoinAddressService;


    @RequestMapping(value = "/getAddress", method = RequestMethod.POST)
    @ResponseBody
    public BaseRespose getAddress(HttpServletRequest request,HttpServletResponse response,String msgTemplate) {
        String userId = String.valueOf(request.getSession().getAttribute("userId"));
        List<TycoinAddress> list=tycoinAddressService.findOneByUserid(Long.valueOf(userId));
        baseRespose.setCode(200);
        baseRespose.setData(list);
        return baseRespose;
    }

	/*********
	 *新增或修改地址
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/address", method = RequestMethod.POST)
	@ResponseBody
	public BaseRespose address(HttpServletRequest request,HttpServletResponse response,String msgTemplate) {
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		String name=(String)  request.getParameter("name");
		String mobile=(String)  request.getParameter("mobile");
		String postcode=(String) request.getParameter("postcode");
		String str_Address=(String) request.getParameter("address");
		long priority= 0;
		try {
			priority = Long.parseLong(request.getParameter("priority"));
		} catch (NumberFormatException e) {}
		long id= 0;
		try {
			id = Long.parseLong(request.getParameter("id"));
		} catch (NumberFormatException e) {}
		if (userId==null||userId.length()<1)
		{
			baseRespose.setCode(4008);
			baseRespose.setMassage("seesion错误");
			return baseRespose;
		}
		TycoinAddress address=id>0?tycoinAddressService.findById(id):new TycoinAddress();
		address.setUserid(Long.valueOf(userId));
		address.setName(name);
		address.setMobile(mobile);
		address.setPostcode(postcode);
		address.setAddress(str_Address);
		if (priority>0){
            address.setPriority(priority);
            removeAddressDefult(request);
        }
		tycoinAddressService.save(address);
		baseRespose.setCode(200);
		baseRespose.setMassage("修改地址成功");
		if (id>0)
			baseRespose.setMassage("添加地址成功");
		return baseRespose;
	}

    /********
     * 清楚地址默认
     * @param request
     */
	public void removeAddressDefult(HttpServletRequest request){
        long userId = (long) request.getSession().getAttribute("userId");
        List<TycoinAddress> list=tycoinAddressService.findOneByUserid(userId);
        if (list==null||list.size()<1)
            return ;
        for (TycoinAddress address : list) {
            if (address.getPriority()==1)
            {
                address.setPriority(0L);
                tycoinAddressService.save(address);
                return;
            }
        }
    }



	/*********
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/sendMsgCode", method = RequestMethod.POST)
	@ResponseBody
	public BaseRespose sendMsgCode(HttpServletRequest request,HttpServletResponse response,String msgTemplate) {
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		TycoinUser user=tycoinUserService.findById(Long.valueOf(userId));
		String email=request.getParameter("email");
		emailCode = DateUtils.getYzm();
		if (user==null)
		{
			baseRespose.setCode(4008);
			baseRespose.setMassage("seesion错误");

		}
		if (SendEmail.sendEmail(email,emailCode,"邮箱验证码")){
			String msg=sendMsgToMoblile(user.getMobile(),resetCode);
			baseRespose.setCode(200);
			baseRespose.setMassage(msg);
			baseRespose.setData(resetCode);
		}
		return baseRespose;
	}




	@RequestMapping(value = "/addEmail", method = RequestMethod.POST)
	@ResponseBody
	public BaseRespose addEmail(HttpServletRequest request,HttpServletResponse response) {
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		TycoinUser tycoinUser=tycoinUserService.findById(Long.valueOf(userId));
		String email=request.getParameter("email");
		String emailCode=request.getParameter("emailCode");
		String vCode=request.getParameter("vcode");
		if (tycoinUser==null)
		{
			baseRespose.setCode(4008);
			baseRespose.setMassage("seesion错误");
			return baseRespose;
		}
		if (!emailCode.equals(emailCode))
		{
			baseRespose.setCode(4011);
			baseRespose.setMassage("seesion错误");
			return baseRespose;
		}
		if (!vCode.equals(resetCode))
		{
			baseRespose.setCode(4011);
			baseRespose.setMassage("seesion错误");
			return baseRespose;
		}
		tycoinUser.setEmail(email);
		tycoinUser.setIsEmail(1);
		tycoinUser.setSecurityLevel(tycoinUser.getSecurityLevel()+1);
		tycoinUserService.save(tycoinUser);
		baseRespose.setCode(200);
		return baseRespose;
	}
	@Autowired
	TycoinUserLoginLogService loginLogService;

	/**********
	 * 获取登录地址  pageNo 页数， pageNum 每页数量 默认10
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/loginLog", method = RequestMethod.POST)
	@ResponseBody
	public BaseRespose loginLog(HttpServletRequest request,HttpServletResponse response) {
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		TycoinUser tycoinUser=tycoinUserService.findById(Long.valueOf(userId));
		int pageNo= 0;
		try {
			pageNo = Integer.parseInt(request.getParameter("pageNo"));
		} catch (NumberFormatException e) {

		}
		try {
			PAGENUM= Integer.parseInt(request.getParameter("pageNum"));
		} catch (NumberFormatException e) {
			PAGENUM=5;
		}
		if (tycoinUser==null)
		{
			baseRespose.setCode(4008);
			baseRespose.setMassage("seesion错误");
			return baseRespose;
		}
		if (pageNo<1)
		{
			baseRespose.setCode(4011);
			baseRespose.setMassage("pageNo参数错误");
			return baseRespose;
		}
		List<TycoinUserLoginLog> loginLogList=loginLogService.findByUserIdAll(Long.parseLong(userId));
		baseRespose.setCode(200);
		baseRespose.setCount(loginLogList.size());
		if(loginLogList.size()<5){
			baseRespose.setData(loginLogList.subList(0,loginLogList.size()));
		}else{
			baseRespose.setData(loginLogList.subList(PAGENUM*(pageNo-1),PAGENUM*pageNo));
		}
		return baseRespose;
	}






	
	
	
}
